package com.du.javaweb.servlet; /**
 * @author : DuJiabao
 * @Date : 2021/3/28 15:06
 * @Project : java-web
 * @File : ${FILE_NAME}
 * @Desc :
 */

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "CookieServlet", value = "/CookieServlet")
public class CookieServlet extends HttpServlet {
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //设置编码格式，防止乱码
    request.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=UTF-8");

    // 获取现有的所有cookie
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
      for (Cookie cookie : cookies) {
        System.out.println(cookie.getName() + " : " + cookie.getValue());
      }
    }

    // 新建cookie，添加到响应中去
    Cookie cookie = new Cookie("key", "value");
    response.addCookie(cookie);
    response.getWriter().write("已发送cookie");

  }

  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doGet(request, response);
  }
}
